import React, { useState, useEffect } from 'react';
import {
  Box,
  Container,
  AppBar,
  Toolbar,
  Typography,
  TextField,
  Button,
  Grid,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  Chip,
  CircularProgress,
  Alert,
  Snackbar,
  Paper,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import BookIcon from '@mui/icons-material/Book';
import './App.css';

function App() {
  const [searchWord, setSearchWord] = useState('');
  const [results, setResults] = useState([]);
  const [sources, setSources] = useState([]);
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [selectedSource, setSelectedSource] = useState(null);

  // 加载词典源和统计信息
  useEffect(() => {
    loadSources();
    loadStats();
  }, []);

  const loadSources = async () => {
    try {
      const result = await window.electronAPI.getSources();
      if (result.success) {
        setSources(result.data);
      }
    } catch (err) {
      console.error('加载词典源失败:', err);
    }
  };

  const loadStats = async () => {
    try {
      const result = await window.electronAPI.getStats();
      if (result.success) {
        setStats(result.data);
      }
    } catch (err) {
      console.error('加载统计信息失败:', err);
    }
  };

  const handleSearch = async () => {
    if (!searchWord.trim()) return;

    setLoading(true);
    setError(null);

    try {
      const result = await window.electronAPI.searchWord(searchWord.trim());
      if (result.success) {
        setResults(result.data);
      } else {
        setError(result.error || '搜索失败');
      }
    } catch (err) {
      setError(err.message || '搜索失败');
    } finally {
      setLoading(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
      {/* 顶部应用栏 */}
      <AppBar position="static" elevation={2}>
        <Toolbar>
          <BookIcon sx={{ mr: 2 }} />
          <Typography variant="h6" component="div" sx={{ flexGrow: 1 }}>
            Memento Dictionary
          </Typography>
        </Toolbar>
      </AppBar>

      {/* 搜索栏 */}
      <Paper sx={{ p: 2, m: 2 }}>
        <Box sx={{ display: 'flex', gap: 2 }}>
          <TextField
            fullWidth
            label="搜索单词"
            variant="outlined"
            value={searchWord}
            onChange={(e) => setSearchWord(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入要搜索的单词..."
            disabled={loading}
          />
          <Button
            variant="contained"
            size="large"
            onClick={handleSearch}
            disabled={loading}
            startIcon={loading ? <CircularProgress size={20} /> : <SearchIcon />}
            sx={{ minWidth: 120 }}
          >
            {loading ? '搜索中' : '搜索'}
          </Button>
        </Box>
      </Paper>

      {/* 主要内容区域 */}
      <Container maxWidth="xl" sx={{ flex: 1, display: 'flex', gap: 2, pb: 2 }}>
        {/* 左侧边栏 - 词典源 */}
        <Paper sx={{ width: 300, p: 2, overflow: 'auto' }}>
          <Typography variant="h6" gutterBottom>
            词典源
          </Typography>
          {stats && (
            <Box sx={{ mb: 2 }}>
              <Grid container spacing={1}>
                <Grid item xs={6}>
                  <Card variant="outlined">
                    <CardContent sx={{ p: 1.5, '&:last-child': { pb: 1.5 } }}>
                      <Typography variant="h4" color="primary">
                        {stats.totalWords || 0}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        总词数
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
                <Grid item xs={6}>
                  <Card variant="outlined">
                    <CardContent sx={{ p: 1.5, '&:last-child': { pb: 1.5 } }}>
                      <Typography variant="h4" color="primary">
                        {stats.enabledSources || 0}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        已启用
                      </Typography>
                    </CardContent>
                  </Card>
                </Grid>
              </Grid>
            </Box>
          )}
          <List>
            {sources.map((source) => (
              <ListItem
                key={source.name}
                button
                selected={selectedSource === source.name}
                onClick={() => setSelectedSource(source.name)}
                sx={{
                  borderRadius: 1,
                  mb: 0.5,
                  '&.Mui-selected': {
                    bgcolor: 'primary.main',
                    color: 'primary.contrastText',
                    '&:hover': {
                      bgcolor: 'primary.dark',
                    },
                  },
                }}
              >
                <ListItemText
                  primary={source.name}
                  secondary={
                    <Box>
                      <Typography variant="caption" display="block">
                        {source.description || '无描述'}
                      </Typography>
                      <Chip
                        label={source.enabled ? '已启用' : '已禁用'}
                        size="small"
                        color={source.enabled ? 'success' : 'default'}
                        sx={{ mt: 0.5 }}
                      />
                    </Box>
                  }
                />
              </ListItem>
            ))}
          </List>
        </Paper>

        {/* 右侧内容 - 搜索结果 */}
        <Paper sx={{ flex: 1, p: 3, overflow: 'auto' }}>
          {error && (
            <Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
              {error}
            </Alert>
          )}

          {results.length === 0 && !loading && (
            <Box
              sx={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                height: '100%',
                color: 'text.secondary',
              }}
            >
              <SearchIcon sx={{ fontSize: 80, mb: 2, opacity: 0.3 }} />
              <Typography variant="h6" gutterBottom>
                开始搜索
              </Typography>
              <Typography variant="body2">
                在上方输入框中输入单词进行搜索
              </Typography>
            </Box>
          )}

          {loading && (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
              <CircularProgress />
            </Box>
          )}

          {results.length > 0 && (
            <Box>
              <Typography variant="h6" gutterBottom>
                搜索结果 ({results.length})
              </Typography>
              <Grid container spacing={2}>
                {results.map((result, index) => (
                  <Grid item xs={12} key={index}>
                    <Card variant="outlined" sx={{ borderLeft: 4, borderLeftColor: 'primary.main' }}>
                      <CardContent>
                        <Typography variant="h5" component="div" gutterBottom>
                          {result.word}
                        </Typography>
                        {result.pronunciation && (
                          <Typography variant="body2" color="text.secondary" gutterBottom>
                            {result.pronunciation}
                          </Typography>
                        )}
                        <Typography variant="body1" paragraph>
                          {result.translation || '无翻译'}
                        </Typography>
                        {result.definition && (
                          <Typography variant="body2" color="text.secondary" paragraph>
                            {result.definition}
                          </Typography>
                        )}
                        <Box sx={{ display: 'flex', gap: 1, mt: 2 }}>
                          <Chip label={result.source} size="small" />
                          {result.language && (
                            <Chip label={result.language} size="small" variant="outlined" />
                          )}
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            </Box>
          )}
        </Paper>
      </Container>

      {/* 错误提示 */}
      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        message={error}
      />
    </Box>
  );
}

export default App;

